<?php

function unproses(){
	$periode_id = get_periode_absen();
	$last_periode_id = get_last_periode_id($periode_id) ;
	if($last_periode_id <= 0){
		return false ;
	}
	$periodes = my_get_data_by_id('pr_periode','periode_id',$periode_id);
	$bulan1 = (int) date('m' , strtotime($periodes['tanggal']));
	$tahun1 = $periodes['tahun'] ;
	if($bulan1 =='01' ){
		$bulan2 = '12';
		$tahun2=$tahun1-1 ;	
	}else{
		$bulan2=$bulan1-1 ;
		$tahun2=$tahun1   ;	
	}		
	//validasi periode absen >= gaji
	$temps=my_get_data_by_id('pr_periode','periode_id',get_periode_gaji()) ;
	$periode_gaji = date('m' , strtotime($temps['tanggal'])) + $temps['tahun'] * 12 ;
	$temps=my_get_data_by_id('pr_periode','periode_id',$last_periode_id) ;
	$periode_absen = date('m' , strtotime($temps['tanggal'])) + $temps['tahun'] * 12 ;
	if($periode_absen < $periode_gaji){
		return false ;
	}
	$query = "TRUNCATE TABLE a_realisasi";
	$result = my_query($query);		

	// MOVE FROM LOG TO REALISASI
	
	$query = "INSERT INTO a_realisasi 
		SELECT 0,karyawan_id,field_tgl,	
		jam_datang,	jam_pulang,	sc_jadwal_kerja_kelompok_id,flag_masuk,flag_pulang		
		FROM a_realisasi_log WHERE periode_id=".$last_periode_id ;	
	$result = my_query($query);		

	// MOVE FROM REALISASI TO a_upload_capture
	$query = "TRUNCATE TABLE a_upload_capture";
	$result = my_query($query);	
	
	$query = "
		SELECT b.nik,a.field_tgl, a.jam_datang,a.jam_pulang 
		FROM a_realisasi a 
		INNER JOIN karyawan b ON b.karyawan_id=a.karyawan_id 
		WHERE !(a.jam_datang='00:00:00' AND a.jam_pulang='00:00:00')"
	;	
	$res = my_query($query);
	while($ey = my_fetch_array($res)){	
		$tgl=(int) substr($ey['field_tgl'],5,2) ;
		if($tgl < 11){
			$tanggal=$tahun1.'-'.sprintf( '%02d',$bulan1) .'-'.sprintf( '%02d',$tgl);
		}else{	
			$tanggal=$tahun2.'-'.sprintf( '%02d',$bulan2) .'-'.sprintf( '%02d',$tgl);
		}
		$datas = array(
			'nik'=>my_type_data_str($ey['nik']), 
			'tanggal'=>my_type_data_str($tanggal), 
			'datang'=>my_type_data_str($ey['jam_datang']),  
			'pulang'=>my_type_data_str($ey['jam_pulang']), 	
		);
		my_insert_record('a_upload_capture' , $datas);
	}
	
	$query = "DELETE FROM a_realisasi_log WHERE periode_id ={$last_periode_id} ";
	$result = my_query($query);		
	
	$query = "DELETE FROM a_absen_payroll WHERE periode_id ={$last_periode_id} ";
	$result = my_query($query);		

	$query = "DELETE FROM a_kalendar_shift WHERE periode_id ={$periode_id} ";
	$result = my_query($query);		
	
	$query = "UPDATE pr_periode SET absen = 'Void' WHERE absen ='Active'" ;
	$result = my_query($query);		
	
	$datas = array(
		'absen'=>my_type_data_str('Active'),	
	);
	my_update_record('pr_periode','periode_id',$last_periode_id,$datas);		

	return true ;
}
